package com.example.usbcamerademo

import android.annotation.SuppressLint
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.ImageButton
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.serenegiant.usb.CameraDialog
import com.serenegiant.usb.USBMonitor
import com.serenegiant.usbcameracommon.UVCCameraHandler
import com.serenegiant.widget.CameraViewInterface
import android.view.Surface;
import com.serenegiant.usb.CameraDialog.CameraDialogParent
import com.serenegiant.usb.USBMonitor.OnDeviceConnectListener
import com.serenegiant.usb.USBMonitor.UsbControlBlock

//kotlin实现
class MainActivity : AppCompatActivity(), CameraDialogParent {

    companion object {
        private const val USE_SURFACE_ENCODER = false
        private const val PREVIEW_WIDTH = 320
        private const val PREVIEW_HEIGHT = 240
        private const val PREVIEW_MODE = 1 // YUV
    }

    // 第一个摄像头相关
    private var mCameraHandler1: UVCCameraHandler? = null
    private var mUVCCameraView1: CameraViewInterface? = null
    private var mCameraButton1: ImageButton? = null

    // 第二个摄像头相关
    private var mCameraHandler2: UVCCameraHandler? = null
    private var mUVCCameraView2: CameraViewInterface? = null
    private var mCameraButton2: ImageButton? = null

    private var mUSBMonitor: USBMonitor? = null
    private var currentCamera = 0 // 标记当前操作的摄像头 (1 or 2)

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.enableEdgeToEdge()
        setContentView(R.layout.activity_main)

        // 初始化第一个摄像头控件
        mCameraButton1 = findViewById(R.id.btn_camera1)
        mCameraButton1!!.setOnClickListener(View.OnClickListener { v: View? -> openCamera(1) })
        val view1 = findViewById<View>(R.id.camera_view1)
        mUVCCameraView1 = view1 as CameraViewInterface
        mUVCCameraView1!!.aspectRatio =
            PREVIEW_WIDTH / PREVIEW_HEIGHT.toDouble()

        // 初始化第二个摄像头控件
        mCameraButton2 = findViewById(R.id.btn_camera2)
        mCameraButton2!!.setOnClickListener(View.OnClickListener { v: View? -> openCamera(2) })
        val view2 = findViewById<View>(R.id.camera_view2)
        mUVCCameraView2 = view2 as CameraViewInterface
        mUVCCameraView2!!.aspectRatio =
            PREVIEW_WIDTH / PREVIEW_HEIGHT.toDouble()

        mUSBMonitor = USBMonitor(this, mOnDeviceConnectListener)


        // 创建两个摄像头处理器
        mCameraHandler1 = UVCCameraHandler.createHandler(
            this, mUVCCameraView1,
            if (USE_SURFACE_ENCODER) 0 else 1, PREVIEW_WIDTH, PREVIEW_HEIGHT, PREVIEW_MODE
        )
        mCameraHandler2 = UVCCameraHandler.createHandler(
            this, mUVCCameraView2,
            if (USE_SURFACE_ENCODER) 0 else 1, PREVIEW_WIDTH, PREVIEW_HEIGHT, PREVIEW_MODE
        )

        var cameraTotal = 0;
        mUSBMonitor!!.deviceList.forEach { usbDevice ->
            // 过滤出真正的UVC摄像头设备
           val usbInfo = USBMonitor.getDeviceInfo(this, usbDevice)
            if (usbInfo?.serial != null && usbInfo.serial != "") {
                Log.i("USB设备信息", "info=${usbInfo}, deviceName=${usbDevice.deviceName},deviceId=${usbDevice.deviceId}")
                cameraTotal++
            }
            // 修改 onCreate 中的设备连接部分
            if (usbDevice.deviceName.equals("/dev/bus/usb/007/004")) {
                // 打开这个摄像头
                val connection = mUSBMonitor!!.openDevice(usbDevice)
                mCameraHandler1!!.open(connection)
                // 延迟启动预览，等待 SurfaceTexture 初始化完成
                Handler(Looper.getMainLooper()).postDelayed({
                    startPreview(1)
                }, 500)
            }

        }
        Log.i("USB设备数量", "cameraTotal=$cameraTotal")





        ViewCompat.setOnApplyWindowInsetsListener(
            findViewById(R.id.main)
        ) { v: View, insets: WindowInsetsCompat ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }



    private fun openCamera(cameraIndex: Int) {
        currentCamera = cameraIndex // 设置当前要操作的摄像头
        CameraDialog.showDialog(this@MainActivity)
    }

    private val mOnDeviceConnectListener: OnDeviceConnectListener =
        object : OnDeviceConnectListener {
            override fun onAttach(device: UsbDevice) {
                Toast.makeText(this@MainActivity, "USB_DEVICE_ATTACHED", Toast.LENGTH_SHORT)
                    .show()
            }

            override fun onConnect(
                device: UsbDevice,
                ctrlBlock: UsbControlBlock,
                createNew: Boolean
            ) {
                // 根据当前选择的摄像头连接到对应的处理器
                when (currentCamera) {
                    1 -> if (mCameraHandler1 != null) {
                        // 如果第一个摄像头已经打开，先关闭
                        if (mCameraHandler1!!.isOpened) {
                            mCameraHandler1!!.close()
                        }
                        mCameraHandler1!!.open(ctrlBlock)
                        startPreview(1)
                    }

                    2 -> if (mCameraHandler2 != null) {
                        // 如果第二个摄像头已经打开，先关闭
                        if (mCameraHandler2!!.isOpened) {
                            mCameraHandler2!!.close()
                        }
                        mCameraHandler2!!.open(ctrlBlock)
                        startPreview(2)
                    }

                    else ->                     // 默认连接到第一个摄像头
                        if (mCameraHandler1 != null) {
                            if (mCameraHandler1!!.isOpened) {
                                mCameraHandler1!!.close()
                            }
                            mCameraHandler1!!.open(ctrlBlock)
                            startPreview(1)
                        }
                }
            }

            override fun onDisconnect(device: UsbDevice, ctrlBlock: UsbControlBlock) {
                // 停止对应摄像头的预览
            }

            override fun onDettach(device: UsbDevice) {
                Toast.makeText(this@MainActivity, "USB_DEVICE_DETACHED", Toast.LENGTH_SHORT)
                    .show()
            }

            override fun onCancel(device: UsbDevice) {
            }
        }

    private fun startPreview(cameraIndex: Int) {
        when (cameraIndex) {
            1 -> if (mCameraHandler1 != null) {
                val st = mUVCCameraView1!!.surfaceTexture
                // 确保之前的预览已经停止
                mCameraHandler1!!.stopPreview()
                mCameraHandler1!!.startPreview(Surface(st))
            }

            2 -> if (mCameraHandler2 != null) {
                val st = mUVCCameraView2!!.surfaceTexture
                // 确保之前的预览已经停止
                mCameraHandler2!!.stopPreview()
                mCameraHandler2!!.startPreview(Surface(st))
            }
        }
    }

    override fun onStart() {
        super.onStart()
        mUSBMonitor!!.register()
    }

    override fun onStop() {
        mUSBMonitor!!.unregister()
        super.onStop()
    }

    public override fun onDestroy() {
        if (mUSBMonitor != null) {
            mUSBMonitor!!.destroy()
            mUSBMonitor = null
        }
        if (mCameraHandler1 != null) {
            mCameraHandler1!!.release()
            mCameraHandler1 = null
        }
        if (mCameraHandler2 != null) {
            mCameraHandler2!!.release()
            mCameraHandler2 = null
        }
        super.onDestroy()
    }

    override fun getUSBMonitor(): USBMonitor {
        return mUSBMonitor!!
    }

    override fun onDialogResult(b: Boolean) {
    }

}
